<template>
  <div class="site-info-container">
    <!-- 站点信息卡片 -->
    <el-card class="info-card" v-if="siteInfo">
      <div slot="header" class="card-header">
        <span>站点信息</span>
        <el-button 
          v-if="userRole === 2" 
          type="primary" 
          size="small" 
          @click="handleEdit"
        >修改站点</el-button>
      </div>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="站点名称">{{ siteInfo.siteName }}</el-descriptions-item>
        <el-descriptions-item label="站点地址">{{ siteInfo.siteAddress }}</el-descriptions-item>
        <el-descriptions-item label="城市">{{ siteInfo.city }}</el-descriptions-item>
        <el-descriptions-item label="区/县">{{ siteInfo.district }}</el-descriptions-item>
        <el-descriptions-item label="联系人姓名">{{ siteInfo.siteUserName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ siteInfo.siteUserPhone }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="siteInfo.status === 1 ? 'success' : 'danger'">
            {{ siteInfo.status === 1 ? '正常' : '暂停营业' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ siteInfo.creatTime }}</el-descriptions-item>
      </el-descriptions>

      <!-- 营业时间 -->
      <div class="business-hours">
        <h4>营业时间</h4>
        <el-table :data="siteInfo.businessHours" border style="width: 100%">
          <el-table-column prop="day" label="时间" width="180"></el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="180"></el-table-column>
          <el-table-column prop="endTime" label="结束时间"></el-table-column>
        </el-table>
      </div>

      <!-- 站点简介 -->
      <div class="site-desc">
        <h4>站点简介</h4>
        <p>{{ siteInfo.siteDesc }}</p>
      </div>
    </el-card>

    <!-- 编辑站点对话框 -->
    <el-dialog title="编辑站点" :visible.sync="editDialogVisible" width="800px">
      <el-form :model="editForm" :rules="rules" ref="editSiteForm" label-width="120px">
        <el-form-item label="站点名称" prop="siteName">
          <el-input v-model="editForm.siteName" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="站点地址" prop="siteAddress">
          <el-input v-model="editForm.siteAddress" class="form-input">
            <el-button slot="append" icon="el-icon-location" @click="openMap"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="editForm.longitude" readonly class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="editForm.latitude" readonly class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="站点联系人电话" prop="siteUserPhone">
          <el-input v-model="editForm.siteUserPhone" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="站点简介" prop="siteDesc">
          <el-input type="textarea" v-model="editForm.siteDesc" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="editForm.city" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="区/县" prop="district">
          <el-input v-model="editForm.district" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="站点状态" prop="status">
          <el-select v-model="editForm.status" class="form-input">
            <el-option label="正常" :value="1"></el-option>
            <el-option label="暂停营业" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="营业时间">
          <div class="business-hours">
            <div class="time-row">
              <span class="time-label">周一至周五：</span>
              <el-time-picker
                v-model="editForm.businessHours[0].startTime"
                placeholder="开始时间"
                format="HH:mm"
                value-format="HH:mm"
                class="time-picker"
              ></el-time-picker>
              <span class="time-separator">至</span>
              <el-time-picker
                v-model="editForm.businessHours[0].endTime"
                placeholder="结束时间"
                format="HH:mm"
                value-format="HH:mm"
                class="time-picker"
              ></el-time-picker>
            </div>
            <div class="time-row">
              <span class="time-label">周六、周日：</span>
              <el-time-picker
                v-model="editForm.businessHours[1].startTime"
                placeholder="开始时间"
                format="HH:mm"
                value-format="HH:mm"
                class="time-picker"
              ></el-time-picker>
              <span class="time-separator">至</span>
              <el-time-picker
                v-model="editForm.businessHours[1].endTime"
                placeholder="结束时间"
                format="HH:mm"
                value-format="HH:mm"
                class="time-picker"
              ></el-time-picker>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 高德地图弹窗 -->
    <el-dialog title="选择位置" :visible.sync="mapVisible" width="80%">
      <el-autocomplete
        v-model="searchQuery"
        :fetch-suggestions="querySearchAsync"
        placeholder="请输入地点名称"
        @select="handleSelect"
        style="margin-bottom: 10px;"
      ></el-autocomplete>
      <div id="container" style="width:100%;height:500px;"></div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import AMapLoader from '@amap/amap-jsapi-loader';

export default {
  name: 'SiteInfo',
  data() {
    return {
      siteInfo: null,
      userRole: null,
      editDialogVisible: false,
      mapVisible: false,
      map: null,
      searchQuery: '',
      placeSearch: null,
      isMapReady: false,
      editForm: {
        id: null,
        siteName: '',
        siteAddress: '',
        longitude: null,
        latitude: null,
        siteUserPhone: '',
        siteUserName: '',
        siteDesc: '',
        city: '',
        district: '',
        status: 1,
        businessHours: [
          {
            day: '周一至周五',
            startTime: '',
            endTime: ''
          },
          {
            day: '周六、周日',
            startTime: '',
            endTime: ''
          }
        ]
      },
      rules: {
        siteName: [
          { required: true, message: '请输入站点名称', trigger: 'blur' },
          { min: 2, max: 50, message: '站点名称长度在2到50个字符之间', trigger: 'blur' }
        ],
        siteAddress: [
          { required: true, message: '请输入站点地址', trigger: 'blur' },
          { min: 5, max: 200, message: '站点地址长度在5到200个字符之间', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '请选择站点位置', trigger: 'change' },
          { pattern: /^-?\d+(\.\d+)?$/, message: '经度格式不正确', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '请选择站点位置', trigger: 'change' },
          { pattern: /^-?\d+(\.\d+)?$/, message: '纬度格式不正确', trigger: 'blur' }
        ],
        siteUserPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        siteUserName: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '联系人姓名长度在2到20个字符之间', trigger: 'blur' }
        ],
        siteDesc: [
          { required: true, message: '请输入站点简介', trigger: 'blur' },
          { min: 10, max: 500, message: '站点简介长度在10到500个字符之间', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请输入城市', trigger: 'blur' },
          { min: 2, max: 20, message: '城市名称长度在2到20个字符之间', trigger: 'blur' }
        ],
        district: [
          { required: true, message: '请输入区/县', trigger: 'blur' },
          { min: 2, max: 20, message: '区/县名称长度在2到20个字符之间', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择站点状态', trigger: 'change' }
        ]
      }
    };
  },
  methods: {
    // 从token中获取用户角色
    getUserRoleFromToken() {
      try {
        const loginUser = JSON.parse(localStorage.getItem("loginUser"));
        if (loginUser && loginUser.token) {
          const base64Url = loginUser.token.split('.')[1];
          const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
          const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
          }).join(''));

          const payload = JSON.parse(jsonPayload);
          if (payload.role !== undefined && payload.role !== null) {
            this.userRole = Number(payload.role);
          } else {
            this.userRole = null;
          }
        }
      } catch (error) {
        console.error('解析token失败:', error);
        this.userRole = null;
      }
    },

    // 获取站点信息
    fetchSiteInfo(siteId) {
      axios.get(`/zsd-merchant/site/find/id`, {
        params: { id: siteId }
      })
        .then(response => {
          if (response.data.code === 200) {
            this.siteInfo = response.data.data;
          } else {
            this.$message.error('获取站点信息失败：' + response.data.msg);
          }
        })
        .catch(error => {
          console.error('获取站点信息出错：', error);
          this.$message.error('获取站点信息出错，请稍后再试');
        });
    },

    // 编辑站点
    handleEdit() {
      this.editDialogVisible = true;
      this.editForm = {
        id: this.siteInfo.id,
        siteName: this.siteInfo.siteName,
        siteAddress: this.siteInfo.siteAddress,
        longitude: this.siteInfo.longitude,
        latitude: this.siteInfo.latitude,
        siteUserPhone: this.siteInfo.siteUserPhone,
        siteUserName: this.siteInfo.siteUserName,
        siteDesc: this.siteInfo.siteDesc,
        city: this.siteInfo.city,
        district: this.siteInfo.district,
        status: this.siteInfo.status,
        businessHours: this.siteInfo.businessHours || [
          {
            day: '周一至周五',
            startTime: '',
            endTime: ''
          },
          {
            day: '周六、周日',
            startTime: '',
            endTime: ''
          }
        ]
      };
    },

    // 打开地图选择
    openMap() {
      this.mapVisible = true;
      this.$nextTick(() => {
        if (!this.map && this.AMap) {
          const AMap = this.AMap;

          // 定义一个函数来初始化地图
          const initMap = (center = [116.397428, 39.90923]) => {
            this.map = new AMap.Map('container', {zoom: 13, center: center});
            var toolbar = new AMap.ToolBar();
            this.map.addControl(toolbar);

            AMap.plugin('AMap.PlaceSearch', () => {
              this.placeSearch = new AMap.PlaceSearch({map: this.map});
              this.isMapReady = true;
            });

            this.map.on('click', (e) => {
              this.editForm.longitude = e.lnglat.getLng();
              this.editForm.latitude = e.lnglat.getLat();
              
              // 获取地址信息
              const geocoder = new AMap.Geocoder();
              geocoder.getAddress([e.lnglat.getLng(), e.lnglat.getLat()], (status, result) => {
                if (status === 'complete' && result.regeocode) {
                  this.editForm.siteAddress = result.regeocode.formattedAddress;
                  this.editForm.city = result.regeocode.addressComponent.city;
                  this.editForm.district = result.regeocode.addressComponent.district;
                }
              });
              
              this.$message.success(`已选择位置：${this.editForm.longitude}, ${this.editForm.latitude}`);
            });
          };

          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
              (position) => {
                const userLocation = [position.coords.longitude, position.coords.latitude];
                initMap(userLocation);
              },
              (error) => {
                console.warn('获取用户位置失败:', error.message);
                initMap();
              }
            );
          } else {
            console.warn('浏览器不支持地理定位');
            initMap();
          }

          const checkPlaceSearchReady = () => {
            if (!this.placeSearch && this.isMapReady === false) {
              setTimeout(checkPlaceSearchReady, 500);
            }
          };
          checkPlaceSearchReady();
        }
      });
    },

    querySearchAsync(queryString, cb) {
      if (queryString) {
        if(this.placeSearch && this.isMapReady){
          this.placeSearch.search(queryString, (status, result) => {
            if (status === 'complete' && result.poiList.count > 0) {
              cb(result.poiList.pois.map(poi => ({
                value: poi.name,
                location: poi.location
              })));
            } else {
              cb([]);
            }
          });
        } else {
          console.error("PlaceSearch instance is not ready.");
          setTimeout(() => {
            this.querySearchAsync(queryString, cb);
          }, 500);
        }
      } else {
        cb([]);
      }
    },

    handleSelect(item) {
      this.editForm.longitude = item.location.lng;
      this.editForm.latitude = item.location.lat;
      this.editForm.siteAddress = item.value;
      this.map.setCenter([item.location.lng, item.location.lat]);
      this.$message.success(`已选择位置：${item.value} (${item.location.lng}, ${item.location.lat})`);
    },

    // 验证营业时间
    validateBusinessHours(rule, value, callback) {
      const index = rule.field.includes('0') ? 0 : 1;
      const startTime = this.editForm.businessHours[index].startTime;
      const endTime = this.editForm.businessHours[index].endTime;

      if (startTime && endTime) {
        const start = new Date(`2000-01-01T${startTime}`);
        const end = new Date(`2000-01-01T${endTime}`);
        
        if (start >= end) {
          callback(new Error('开始时间不能大于或等于结束时间'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },

    // 提交编辑表单
    submitEditForm() {
      this.$refs['editSiteForm'].validate((valid) => {
        if (valid) {
          // 验证营业时间
          const isBusinessHoursValid = this.editForm.businessHours.every(hours => {
            if (hours.startTime && hours.endTime) {
              const start = new Date(`2000-01-01T${hours.startTime}`);
              const end = new Date(`2000-01-01T${hours.endTime}`);
              return start < end;
            }
            return true;
          });

          if (!isBusinessHoursValid) {
            this.$message.error('营业时间设置不正确，开始时间不能大于或等于结束时间');
            return;
          }

          const updateSiteForm = {
            ...this.editForm,
            businessHours: this.editForm.businessHours.filter(hours => hours.startTime && hours.endTime)
          };
          
          axios.put('/zsd-merchant/site/update', updateSiteForm)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success('编辑站点成功');
                this.editDialogVisible = false;
                this.fetchSiteInfo(this.siteInfo.id);
              } else {
                this.$message.error(response.data.msg || '编辑站点失败');
              }
            })
            .catch(error => {
              console.error('Error:', error);
              this.$message.error('编辑站点失败');
            });
        } else {
          console.log('验证失败');
          return false;
        }
      });
    }
  },
  mounted() {
    this.getUserRoleFromToken();
    
    // 获取管理员个人信息以获取站点ID
    axios.get('/zsd-permission/admin-info/selAdminInfo')
      .then(response => {
        if (response.data.code === null) {
          const adminInfo = response.data.data;
          if (adminInfo.siteId) {
            this.fetchSiteInfo(adminInfo.siteId);
          }
        } else {
          this.$message.error('获取个人信息失败：' + response.data.msg);
        }
      })
      .catch(error => {
        console.error('获取个人信息出错：', error);
        this.$message.error('获取个人信息出错，请稍后再试');
      });
    
    // 设置安全密钥
    window._AMapSecurityConfig = {
      securityJsCode: '3242f3455132c5fd8bbd976165cf3edd'
    };

    AMapLoader.load({
      key: "96b8191f938c9fee3541bd080df37ac1", 
      version: "2.0",
      plugins: ['AMap.ToolBar', 'AMap.PlaceSearch']
    }).then((AMap) => {
      this.AMap = AMap;
      console.log('高德地图API加载成功');
    }).catch(e => {
      console.error('地图加载失败:', e);
    });
  }
};
</script>

<style scoped>
.site-info-container {
  padding: 20px;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.business-hours,
.site-desc {
  margin-top: 20px;
}

.business-hours h4,
.site-desc h4 {
  margin-bottom: 10px;
  color: #606266;
}

.site-desc p {
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

.form-input {
  width: 400px !important;
}

.business-hours {
  width: 100%;
}

.time-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.time-row:last-child {
  margin-bottom: 0;
}

.time-label {
  min-width: 100px;
  text-align: right;
  margin-right: 10px;
}

.time-picker {
  width: 140px !important;
}

.time-separator {
  margin: 0 10px;
}

.el-textarea {
  width: 400px !important;
}

.el-select {
  width: 400px !important;
}

.el-dialog .el-form {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}
</style>
